// ============================================================================
// KeywordCrawlWindow 实体定义 - 追踪关键字爬取时间窗口
// ============================================================================

import {
  Entity,
  PrimaryColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index
} from 'typeorm'

/**
 * 关键字爬取窗口实体
 * 记录每个关键字的爬取时间范围，支持增量爬取策略
 */
@Entity('keyword_crawl_windows')
@Index(['keyword'], { unique: true })
@Index(['updatedAt'])
export class KeywordCrawlWindow {
  @PrimaryColumn({ type: 'varchar' })
  keyword: string

  /**
   * 最早爬取到的微博创建时间（keywordStartTime）
   */
  @Column({ 
    name: 'start_time', 
    type: 'datetime',
    nullable: true,
    comment: '最早爬取到的微博创建时间'
  })
  startTime?: Date

  /**
   * 最晚爬取到的微博创建时间（keywordEndTime）
   */
  @Column({ 
    name: 'end_time', 
    type: 'datetime',
    nullable: true,
    comment: '最晚爬取到的微博创建时间'
  })
  endTime?: Date

  /**
   * 是否还有更多历史帖子需要爬取
   * false 表示历史帖子已经爬取完毕
   */
  @Column({ 
    name: 'has_more_history', 
    type: 'integer', 
    default: 1,
    comment: '是否还有更多历史帖子',
    transformer: {
      to: (value: boolean) => value ? 1 : 0,
      from: (value: number) => Boolean(value)
    }
  })
  hasMoreHistory: boolean

  /**
   * 最后一次历史爬取时间
   * 用于控制历史爬取频率
   */
  @Column({ 
    name: 'last_history_crawl_at', 
    type: 'datetime',
    nullable: true,
    comment: '最后一次历史爬取时间'
  })
  lastHistoryCrawlAt?: Date

  /**
   * 爬取统计信息
   */
  @Column({ 
    name: 'total_posts_crawled', 
    type: 'integer', 
    default: 0,
    comment: '总爬取帖子数量'
  })
  totalPostsCrawled: number

  /**
   * 最新帖子爬取统计
   */
  @Column({ 
    name: 'latest_posts_crawled', 
    type: 'integer', 
    default: 0,
    comment: '最新帖子爬取数量'
  })
  latestPostsCrawled: number

  /**
   * 历史帖子爬取统计
   */
  @Column({ 
    name: 'history_posts_crawled', 
    type: 'integer', 
    default: 0,
    comment: '历史帖子爬取数量'
  })
  historyPostsCrawled: number

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date

  /**
   * 检查是否需要进行历史爬取
   * @param historyCrawlInterval 历史爬取间隔（毫秒），默认24小时
   */
  shouldCrawlHistory(historyCrawlInterval: number = 24 * 60 * 60 * 1000): boolean {
    if (!this.hasMoreHistory) {
      return false
    }

    if (!this.lastHistoryCrawlAt) {
      return true
    }

    const now = new Date()
    const timeSinceLastCrawl = now.getTime() - this.lastHistoryCrawlAt.getTime()
    return timeSinceLastCrawl >= historyCrawlInterval
  }

  /**
   * 更新时间窗口
   * @param newPosts 新爬取的微博数据
   * @param type 爬取类型：'latest' | 'history'
   */
  updateWindow(newPosts: Array<{ created_at: string | Date }>, type: 'latest' | 'history'): void {
    if (newPosts.length === 0) {
      if (type === 'history') {
        this.hasMoreHistory = false
        this.lastHistoryCrawlAt = new Date()
      }
      return
    }

    // 解析日期并找到最小和最大时间
    const dates = newPosts
      .map(post => new Date(post.created_at))
      .filter(date => !isNaN(date.getTime()))
      .sort((a, b) => a.getTime() - b.getTime())

    if (dates.length === 0) {
      return
    }

    const minDate = dates[0]!
    const maxDate = dates[dates.length - 1]!

    // 更新时间范围
    if (!this.startTime || minDate < this.startTime) {
      this.startTime = minDate
    }

    if (!this.endTime || maxDate > this.endTime) {
      this.endTime = maxDate
    }

    // 更新统计信息
    this.totalPostsCrawled += newPosts.length
    if (type === 'latest') {
      this.latestPostsCrawled += newPosts.length
    } else {
      this.historyPostsCrawled += newPosts.length
      this.lastHistoryCrawlAt = new Date()
    }
  }

  /**
   * 重置窗口（强制重新爬取）
   */
  reset(): void {
    this.startTime = undefined
    this.endTime = undefined
    this.hasMoreHistory = true
    this.lastHistoryCrawlAt = undefined
    this.totalPostsCrawled = 0
    this.latestPostsCrawled = 0
    this.historyPostsCrawled = 0
  }

  /**
   * 获取时间窗口大小（天数）
   */
  getWindowSizeDays(): number | null {
    if (!this.startTime || !this.endTime) {
      return null
    }

    const diffMs = this.endTime.getTime() - this.startTime.getTime()
    return Math.ceil(diffMs / (1000 * 60 * 60 * 24))
  }

  /**
   * 获取爬取状态摘要
   */
  getSummary(): {
    keyword: string
    windowSize: string
    totalPosts: number
    hasMoreHistory: boolean
    lastUpdate: string
  } {
    return {
      keyword: this.keyword,
      windowSize: this.getWindowSizeDays() 
        ? `${this.getWindowSizeDays()} 天 (${this.startTime?.toLocaleDateString()} ~ ${this.endTime?.toLocaleDateString()})`
        : '未设置',
      totalPosts: this.totalPostsCrawled,
      hasMoreHistory: this.hasMoreHistory,
      lastUpdate: this.updatedAt.toLocaleString()
    }
  }
}
